//
//  GPMapVC.m
//  PFAmapDemo
//
//  Created by 原鹏飞 on 2018/11/1.
//  Copyright © 2018 ypf. All rights reserved.
//

#import "GPMapVC.h"

#import <MAMapKit/MAMapKit.h>           // 高德地图类
#import <AMapNaviKit/AMapNaviKit.h>     // 高德导航类

#import "PFRoutePlanVC.h"               // 规划路线的控制器


#import "GPNaviVC.h"                    // 导航VC

#import "GPNearbyShopTBCell.h"
#import "GPNearbyShopTBCellModel.h"

@interface GPMapVC () <MAMapViewDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) AMapLocationManager *locationManager;     // 高德定位类
@property (nonatomic, strong) MAMapView *mapView;   // 高德地图视图

@property (nonatomic, strong) AMapNaviPoint *startPoint;    // 导航起点
@property (nonatomic, strong) AMapNaviPoint *endPoint;      // 导航终点
@property (nonatomic, strong) AMapNaviCompositeManager *compositeManager;   // 导航组件类


@property (nonatomic, strong) CLLocation *currentLocation;  // 用户当前位置
@property (nonatomic, strong) CLLocation *targetLocation;
@property (nonatomic, strong) NSMutableArray<GPNearbyShopTBCellModel *> *modelArr;


@property (nonatomic, strong) UIButton *exitBtn;    // 退出按钮
@property (nonatomic, strong) UITableView *nearbyShopTB;
@property (nonatomic, strong) UIButton *dragBtn;

@end

@implementation GPMapVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initData];
    
    [self setupUI];
}


#pragma mark - 初始化

- (AMapLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[AMapLocationManager alloc] init];
        _locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        _locationManager.locationTimeout = 2;
        _locationManager.reGeocodeTimeout = 2;
    }
    return _locationManager;
}


- (CLLocation *)currentLocation {
    if (!_currentLocation) {
        
        __block CLLocation *location;
        [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
            // 判断定位是否成功
            if (!error && location) {
                location = location;
            }
        }];
        
        _currentLocation = [[CLLocation alloc] initWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
    }
    return _currentLocation;
}


/**
 初始化附近店铺列表的假数据
 */
- (void)initData {
    
    GPNearbyShopTBCellModel *model1 = [[GPNearbyShopTBCellModel alloc] init];
    model1.shopName = @"中国华润大厦";
    model1.address = @"深圳市南山区海德一道与科苑路交汇处";
    model1.latitude = 22.520424f;
    model1.longitude = 113.953125f;
    
    GPNearbyShopTBCellModel *model2 = [[GPNearbyShopTBCellModel alloc] init];
    model2.shopName = @"中海油大厦";
    model2.address = @"深圳市南山区后海滨路与创业路交汇处";
    model2.latitude = 22.517973f;
    model2.longitude = 113.945759f;
    
    GPNearbyShopTBCellModel *model3 = [[GPNearbyShopTBCellModel alloc] init];
    model3.shopName = @"深圳湾创业广场";
    model3.address = @"深圳市南山区软件产业基地6栋";
    model3.latitude = 22.52913f;
    model3.longitude = 113.944554f;
    
    GPNearbyShopTBCellModel *model4 = [[GPNearbyShopTBCellModel alloc] init];
    model4.shopName = @"金蝶大厦";
    model4.address = @"南山高新技术开发区科技南十二路2号";
    model4.latitude = 22.539728f;
    model4.longitude = 113.961553f;
    
    GPNearbyShopTBCellModel *model5 = [[GPNearbyShopTBCellModel alloc] init];
    model5.shopName = @"世界之窗";
    model5.address = @"南山区深南大道9037号世界之窗";
    model5.latitude = 22.542939f;
    model5.longitude = 113.980737f;
    
    GPNearbyShopTBCellModel *model6 = [[GPNearbyShopTBCellModel alloc] init];
    model6.shopName = @"深圳图书馆";
    model6.address = @"深圳市福田区福中一路2001号";
    model6.latitude = 22.551343f;
    model6.longitude = 114.063825f;
    
    GPNearbyShopTBCellModel *model7 = [[GPNearbyShopTBCellModel alloc] init];
    model7.shopName = @"广东梧桐山国家森林公园";
    model7.address = @"沙头角梧桐路2002号";
    model7.latitude = 22.5838f;
    model7.longitude = 114.221632f;
    
    GPNearbyShopTBCellModel *model8 = [[GPNearbyShopTBCellModel alloc] init];
    model8.shopName = @"大梅沙海滨公园";
    model8.address = @"深圳市盐田区盐梅路";
    model8.latitude = 22.598196f;
    model8.longitude = 114.314011f;
    
    GPNearbyShopTBCellModel *model9 = [[GPNearbyShopTBCellModel alloc] init];
    model9.shopName = @"莲花山公园";
    model9.address = @"广东省深圳市福田区红荔路6030号";
    model9.latitude = 22.559257f;
    model9.longitude = 114.065193f;
    
    GPNearbyShopTBCellModel *model10 = [[GPNearbyShopTBCellModel alloc] init];
    model10.shopName = @"罗浮山风景名胜区";
    model10.address = @"惠州市博罗县长宁镇罗浮山风景名胜区";
    model10.latitude = 23.270566f;
    model10.longitude = 114.04283f;
    
    // 手写假数据 latitude纬度，longitude经度
    _modelArr = [NSMutableArray arrayWithObjects:model1, model2, model3, model4, model5, model6, model7, model8, model9, model10, nil];
}


/**
 初始化UI
 */
- (void)setupUI {
    self.view.backgroundColor = [UIColor orangeColor];
    
    [self myAddSubviews];
    
    // 将假数据对应的大头针添加到地图上
    for (GPNearbyShopTBCellModel *model in self.modelArr) {
        [self pf_addPointWithLatitude:model.latitude andLongitude:model.longitude];
    }
    
}


/**
 添加子控件
 */
- (void)myAddSubviews {
    
    // 添加地图视图
    _mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.mapView];
    // 设置地图视图属性
    self.mapView.delegate = self;
    self.mapView.desiredAccuracy = kCLLocationAccuracyBest; // 设置定位精度
    self.mapView.distanceFilter = 20.0f; // 设置刷新定位的距离
    self.mapView.mapType = MAMapTypeNavi;   // 设置地图样式
    self.mapView.showsCompass = NO; // 设置不显示指南针
    self.mapView.compassOrigin = CGPointMake(self.mapView.compassOrigin.x, 22); // 设置指南针位置
    self.mapView.showsScale = NO;   // 设置不显示比例尺
    self.mapView.scaleOrigin = CGPointMake(self.mapView.scaleOrigin.x, 22); // 设置比例尺的位置
    self.mapView.zoomEnabled = YES; // 支持缩放
    [self.mapView setZoomLevel:12.f animated:YES]; // 设置初始缩放等级
    [self.mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];   // 设置地图跟随用户移动
    self.mapView.showsUserLocation = YES;   // 在地图上显示用户位置
    _currentLocation = self.mapView.userLocation;   // 保存一下用户的当前位置
    
    // 添加退出按钮
    _exitBtn = [UIButton pf_buttonWithTitle:@"X" andTitleColor:[UIColor redColor] andBorderWidth:0.5f andBorderColor:[UIColor.redColor CGColor]];
    [_exitBtn addTarget:self action:@selector(clickExitBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_exitBtn];
    [_exitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(50);
        make.left.equalTo(self.view).offset(20);
        make.height.width.mas_equalTo(44);
    }];
    
    // 添加店铺列表
    _nearbyShopTB = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.nearbyShopTB registerClass:[GPNearbyShopTBCell class] forCellReuseIdentifier:NSStringFromClass(GPNearbyShopTBCell.class)];
    self.nearbyShopTB.dataSource = self;
    self.nearbyShopTB.delegate = self;
    self.nearbyShopTB.rowHeight = 80;
    [self.view addSubview:self.nearbyShopTB];
    [self.nearbyShopTB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(10);
        make.right.equalTo(self.view).offset(-10);
        make.bottom.equalTo(self.view);
        make.height.mas_equalTo(self.view.bounds.size.height * 0.5);
    }];
    
    // 添加拖拽按钮
    _dragBtn = [[UIButton alloc] init];
    self.dragBtn.layer.borderColor = [UIColor redColor].CGColor;
    self.dragBtn.layer.borderWidth = 0.5f;
    [self.view addSubview:self.dragBtn];
    [self.dragBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.nearbyShopTB.mas_top);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(90);
    }];
    
    UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGRAct:)];
    [self.dragBtn setUserInteractionEnabled:YES];
    [self.dragBtn addGestureRecognizer:panGR];
    
}


- (void)initNearbyShopTB {
    
}


- (void)initDragBtn {
    
}


#pragma mark - 处理拖拽TB的手势

/**
 处理拖拽手势的方法
 
 @param panGes 拖拽手势
 */
- (void)panGRAct: (UIPanGestureRecognizer *)panGes{
    
    CGPoint offset = [panGes translationInView:self.view];
    if (offset.y < 0 && - offset.y >= 100) {
        NSLog(@"向上");
        [self.nearbyShopTB mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(self.view.bounds.size.height * 0.5);
        }];
    }
    
    if (offset.y > 0 && offset.y >= 100) {
        NSLog(@"向下");
        [self.nearbyShopTB mas_updateConstraints:^(MASConstraintMaker *make) {
            //            make.left.equalTo(self.view).offset(10);
            //            make.right.equalTo(self.view).offset(-10);
            //            make.bottom.equalTo(self.view);
            make.height.mas_equalTo(80);
        }];
    }
}


#pragma mark - 地图相关方法

/**
 设置地图视图的中心点
 
 @param mapView 目标地图视图
 */
- (void)resetCenterWithMapView:(MAMapView *)mapView {
    
    if (mapView && [self pf_currentLocation]) {
        [mapView setCenterCoordinate:[self pf_currentLocation].coordinate animated:YES];
    }
}



- (CLLocation *)pf_currentLocation {
    
    
    __block CLLocation *currentLocation = nil;
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        // 判断定位是否成功
        if (!error && location) {
            currentLocation = location;
        }
    }];
    return currentLocation;
}


- (void)pf_navigateWithLatitude:(CLLocationDegrees)latitude andLongitude:(CLLocationDegrees)longitude andName:(NSString *)name {
    
    // 推出导航控制器
    GPNaviVC *naviVC = [[GPNaviVC alloc] init];
    naviVC.currentUL = self.mapView.userLocation;
    naviVC.targetLocation = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    [self.navigationController pushViewController:naviVC animated:YES];
    
//    // 导航组件的配置类
//    AMapNaviCompositeUserConfig *config = [[AMapNaviCompositeUserConfig alloc] init];
//    //传入终点坐标
//    [config setRoutePlanPOIType:AMapNaviRoutePlanPOITypeEnd location:[AMapNaviPoint locationWithLatitude:latitude longitude:longitude] name:name POIId:nil];
//
//    dispatch_async(dispatch_get_main_queue(), ^{
//        // 通过present的方式显示导航组件页面
//        // 注意：此函数涉及到UI操作，请在主线程中调用，否则无效.
//        [self.compositeManager presentRoutePlanViewControllerWithOptions:config];
//    });
    
    

}


// 添加大头针
- (void)pf_addPointWithLatitude:(CLLocationDegrees)latitude andLongitude:(CLLocationDegrees)longitude {
    //    self.testArr[0] valueForKey:@"latitude"
    // 创建坐标
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = latitude;
    coordinate.longitude = longitude;
    
    // 创建点
    MAPointAnnotation *pointAnnottion = [[MAPointAnnotation alloc] init];
    pointAnnottion.coordinate = coordinate;
    [self.mapView addAnnotation:pointAnnottion];
}


/**
 退出地图
 */
- (void)clickExitBtn {
    [self dismissViewControllerAnimated:YES completion:^{
        NSLog(@"退出地图");
    }];
}


#pragma mark - MAMapViewDelegate

/**
 * @brief 位置或者设备方向更新后，会调用此函数
 * @param mapView 地图View
 * @param userLocation 用户定位信息(包括位置与设备方向等数据)
 * @param updatingLocation 标示是否是location数据更新, YES:location数据更新 NO:heading数据更新
 */
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    
    /**
    // 保存用户的当前位置
    self.currentLocation = userLocation;
    
    // 可以创建一个经纬度点
    MAPointAnnotation *point = [[MAPointAnnotation alloc] init];
    point.coordinate = userLocation.location.coordinate;
    
    // 可以获取一个位置
    CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:userLocation.location.coordinate.latitude longitude:userLocation.location.coordinate.longitude];
    
    // 可以获取逆地理信息
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init]; // 初始化编码器
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        // 获取当前城市位置信息，其中CLPlacemark包括name、thoroughfare、subThoroughfare、locality、subLocality等详细信息
        CLPlacemark *mark = [placemarks lastObject];
        NSString *cityName = mark.locality;
        NSLog(@"城市 - %@", cityName);
        //        self.currentCity  = cityName;
    }];
    */
    
}


// 添加大头针会调用此代理方法，其中可设置大头针的图片、点击大头针弹出的气泡视图
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    
    //大头针标注
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {//判断是否是自己的定位气泡，如果是自己的定位气泡，不做任何设置，显示为蓝点，如果不是自己的定位气泡，比如大头针就会进入
        
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        
        MAAnnotationView*annotationView = (MAAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        
        if (annotationView == nil) {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        
        annotationView.frame = CGRectMake(0, 0, 100, 100);
        annotationView.canShowCallout= YES; //设置气泡可以弹出，默认为NO
        //annotationView.animatesDrop = YES;    //设置标注动画显示，默认为NO
        annotationView.draggable = YES;     //设置标注可以拖动，默认为NO
        //annotationView.pinColor = MAPinAnnotationColorPurple;
        
        //设置大头针显示的图片
        annotationView.image = [UIImage imageNamed:@"icon_nearby_locateBtn"];
        
        //点击大头针显示的左边的视图
        UIImageView *imageV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"img_default_shop"]];
        annotationView.leftCalloutAccessoryView = imageV;
        
        //点击大头针显示的右边视图
        UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 50)];
        rightButton.backgroundColor = [UIColor grayColor];
        [rightButton setTitle:@"导航" forState:UIControlStateNormal];
        annotationView.rightCalloutAccessoryView = rightButton;

        //annotationView.image = [UIImage imageNamed:@"redPin"];
        
        return annotationView;
    }
    
    return nil;
}


#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GPNearbyShopTBCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(GPNearbyShopTBCell.class) forIndexPath:indexPath];
    cell.model = self.modelArr[indexPath.row];
    return cell;
}


#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"去这家店：%zd", indexPath.row);
//    [self pf_navigateWithLatitude:self.modelArr[indexPath.row].latitude
//                     andLongitude:self.modelArr[indexPath.row].longitude
//                          andName:self.modelArr[indexPath.row].shopName];
    
    PFRoutePlanVC *routePlanVC = [[PFRoutePlanVC alloc] init];
    
    routePlanVC.startPoint = [AMapNaviPoint locationWithLatitude:self.currentLocation.coordinate.latitude longitude:self.currentLocation.coordinate.longitude];
    routePlanVC.endPoint = [AMapNaviPoint locationWithLatitude:self.modelArr[indexPath.row].latitude longitude:self.modelArr[indexPath.row].longitude];
    
    [self.navigationController pushViewController:routePlanVC animated:YES];
    
}


@end
